--[[
dht11
]]
--==============IMPORT================`
local pilib = require("libs/pilib")
local event = require("libs/event")
local PIN_MODE = PIN_MODE

local print = print
--==============IMPORT================`
-- 左移
local function leftShift(num, shift)
    
    print(num, shift, "-->>shift")
    return math.floor(num * (2 ^ shift));
end

-- 二进制转int
local function bufToInt32(numlist)
    local num = 0;
    for i = 1, #numlist do
        num = num + leftShift(numlist[i], #numlist - i)
    end
    return num;
end


local dht11 = {}

function dht11.execute(pinidx)
    --delay 1 sec
    pilib.delay(1000)

    pilib.pinMode(pinidx, PIN_MODE["OUTPUT"])
    pilib.digitalWrite(pinidx, PIN_MODE["LOW"])
    
    pilib.delay(20)--delay 18
    pilib.digitalWrite(pinidx, PIN_MODE["HIGH"])
    pilib.pinMode(pinidx, PIN_MODE["INPUT"])
    
    local ret, nidx
    local SIGN_CNT = 40
    
    ret = {}
    nidx = 0
    
    local err_break = 0
    repeat 
        print("wait in low")
    until (pilib.digitalRead(pinidx) ~= PIN_MODE["LOW"])

    repeat
        print("wait in high")
    until (pilib.digitalRead(pinidx) ~= PIN_MODE["HIGH"])
        
    while (true)
    do

        if (nidx < SIGN_CNT) then
            repeat 
                print ("wait first 50us")
            until (GPIO.input(channel) ~= GPIO.LOW)
            
            print("wait secode 30-70us")
            pilib.delayMicroseconds(30)
            if pilib.digitalRead(pinidx) == PIN_MODE["HIGH"] then 
                table.insert(ret, 1)
            else 
                table.insert(ret, 0)
            end
            nidx = nidx + 1
        else
            break
        end
    end


    -- end   
    for _, v in pairs(ret) do
        print(v, "-->>v")
    end
    function table.sub(tb, stari, ende)
        local ret = {}
        for i = stari, ende do
            table.insert(ret, tb[i])
        end
        return ret
    end
    local rh_int = bufToInt32(table.sub(ret, 1, 8))
    local rh_float = bufToInt32(table.sub(ret, 9, 16))
    print(rh_int, rh_float, "int, float-->>rh")
    local tp_int = bufToInt32(table.sub(ret, 17, 24))
    local tp_float = bufToInt32(table.sub(ret, 25, 32))
    print(tp_int, tp_float, "int, float-->>tp")
    
    local chk = bufToInt32(table.sub(ret, 33, 40))
    print(chk, "--->>chk", chk == (rh_int + rh_float + tp_int + tp_float))

end

return dht11


